/* eslint-disable array-callback-return */
import fetch from 'dva/fetch';
import React, { Component } from 'react';
import { Form, Layout, Row, Col, Tabs, Spin, Modal, message } from 'antd';
import Toolbar from '../../Common/ToolBar/ToolBar';
import styles from '../../../index.less';
import JurGroupData from './JurGroupData';
import JurUserData from './JurUserData';
import JurUserGroupData from './JurUserGroupData';
import JurGroupUserData from './JurGroupUserData';
import TabJurCon from './TabJurCon';
import TabJurTreeCon from './TabJurTreeCon';
import * as commonFunc from '../../Common/commonFunc';
import baseHigher from '../../Common/baseHigher';
import * as config from '../../../utils/config';

const { Header, Content } = Layout;
const { TabPane } = Tabs;
const { confirm } = Modal;

class JurisdictionAllotComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sTabId: props.app.currentPane.key,
      btnData: config.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' },
      sActiveId: '', /* 窗体Id */
      loading: false,
      groupsId: '', /* 组权限sId */
      tabJurCon: '', /* 权限名称 */
      tabHasJur: '', /* 已有权限 */
      currentKey: '', /* 当前key */
      groupAuth: [], /* 组权限 */
      treeData: [], /* 树 */
      treeDataOld: [],
      allKeys: [], /* 所有节点 */
      allChildKeys: [], /* 所有子点节 */
      checkedKeys: [], /* 当前选中节点 */
      authFlag: '', /* 组权限还是人员权限 */
      unCheckedKey: [],
      allChildTree: [], /* 所有子节点和名字 */
    };
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    /* 配置 */
    const { sDataListTabId, formRoute, loading } = dataList;
    /* 窗体全部配置 */
    const masterConfig = commonFunc.getWindowConfig('NOTABLE', nextProps.formData);
    if (nextProps.sTabId === sDataListTabId && nextProps.formRoute === formRoute && nextProps.formData.length > 0) {
      const { formId } = nextProps;
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      /* 窗体显示配置 */
      const masterShowConfig = commonFunc.getConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
      const tabJurCon = masterConfig.gdsconfigformslave.filter(item => (item.sControlName.toLowerCase() === 'tabjurcon'))[0];
      const tabHasJur = masterConfig.gdsconfigformslave.filter(item => (item.sControlName.toLowerCase() === 'tabhasjur'))[0];
      /* 从表配置 */
      this.setState({
        masterConfig, masterShowConfig, sActiveId: formId, tabJurCon, tabHasJur,
      });
    }
  }

  /* 取消 */
  handleCancel =(type) => {
    const onhandleOk = this.handleOk;
    confirm({
      title: '确定要取消?',
      onOk() {
        onhandleOk(type);
      },
      onCancel() {},
    });
  };

  /* 确认取消 */
  handleOk = () => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === this.props.app.currentPane.key) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== this.props.app.currentPane.key);
    let currentPane;
    if (lastIndex >= 0) {
      currentPane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      currentPane = panes[lastIndex + 1];
    } else {
      currentPane = { title: '', route: '', key: '0' };
    }
    this.props.onRemovePane(panes, currentPane);
  };

  /* 保存 */
  handleSubmit = () => {
    const {
      unCheckedKey, authFlag, currentKey, sActiveId, sTabId,
    } = this.state;
    if (authFlag === '') {
      return message.warning('请选择组员权或人员权限');
    }
    const value = {
      data: unCheckedKey,
    };
    if (authFlag === 'user') {
      value.sUserId = currentKey;
    } else {
      value.sJurisdictionClassifyId = currentKey;
    }
    const { dispatch } = this.props;
    const url = `${config.server_host}sysjurisdiction/addSysjurisdiction?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url,
        sTabId,
        value,
        returnType: 'CUD',
      },
    });
  };

  handleGroupsId = (groupsId) => {
    /* 点击权限，获取组成员 */
    this.setState({ currentKey: groupsId, authFlag: 'group' });
    const { sActiveId, sTabId } = this.state;
    const { dispatch } = this.props;
    setTimeout(() => {
      const dataUrl = `${config.server_host}sysjurisdiction/getsUserGroupId/${groupsId}?sModelsId=${sActiveId}`;
      dispatch({ type: 'content/getUrlData', payload: { url: dataUrl, sTabId, componentName: 'jurUserGroup' } });
      if (groupsId !== '') {
        const { token } = this.props.app;
        const jurUrl = `${config.server_host}sysjurisdiction/getHaveAuthorityGroupId/${groupsId}?sModelsId=${sActiveId}`;
        const options = {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
        };
        fetch(jurUrl, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            const { rows } = json.dataset;
            if (rows[0] === null || rows[0].sKeys !== undefined) {
              const groupAuth = rows[0] === null ? [] : rows[0].sKeys.split(',');
              const { treeDataOld, allKeys, allChildKeys } = this.state;
              const checkedKey = JSON.parse(JSON.stringify(allChildKeys));
              const treeDatas = JSON.parse(JSON.stringify(treeDataOld));
              const checkedHaveKey = JSON.parse(JSON.stringify(allKeys)); /* 已有权限, 含父节点 */
              treeDatas.forEach((child) => {
                const index = groupAuth.findIndex(item => item === child.key);
                child.disabled = false;
                if (index >= 0) {
                  const checkIndex = checkedKey.findIndex(item => item === groupAuth[index]);
                  const checkHaveIndex = checkedHaveKey.findIndex(item => item === groupAuth[index]);
                  checkedKey.splice(checkIndex, 1);
                  checkedHaveKey.splice(checkHaveIndex, 1);
                }
                if (child.children !== undefined && child.children.length > 0) {
                  this.handleGroupAuthData(child.children, groupAuth, checkedKey, checkedHaveKey);
                }
                this.setState({
                  checkedHaveKey,
                  checkedKeys: checkedKey,
                  treeData: treeDatas,
                  groupAuth,
                });
              });
            }
          }
        });
      }
    });
  };

  handleUserGroupsId = (userGroupsId) => {
    /* 根据用户账号，获取相应组 */
    this.setState({ currentKey: userGroupsId, authFlag: 'user' });
    const { sActiveId, sTabId } = this.state;
    const { dispatch } = this.props;
    setTimeout(() => {
      const dataUrl = `${config.server_host}sysjurisdiction/getGroupUserId/${userGroupsId}?sModelsId=${sActiveId}`;
      dispatch({ type: 'content/getUrlData', payload: { url: dataUrl, sTabId, componentName: 'jurGroupUserData' } });
      if (userGroupsId !== '') {
        const { token } = this.props.app;
        const jurUrl = `${config.server_host}sysjurisdiction/getHaveAuthorityUserId/${userGroupsId}?sModelsId=${sActiveId}`;
        const options = {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
        };
        fetch(jurUrl, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            const { rows } = json.dataset;
            if (rows[0].groupAuth !== undefined) {
              /* 人权限 */
              const groupAuth = rows[0].groupAuth === null ? [] : rows[0].groupAuth.sKeys.split(',');
              const userAuth = rows[0].userAuth === null ? [] : rows[0].userAuth.sKeys.split(',');
              const auth = [];
              groupAuth.forEach((child) => {
                const index = userAuth.findIndex(item => item === child);
                if (index === -1) {
                  auth.push({ key: child, flag: '1' }); /* 1 代表有的权限，并且可以编辑 */
                } else {
                  auth.push({ key: child, flag: '0' }); /* 0 代表没有的权限，并且可以编辑 */
                }
              });
              const { treeDataOld, allKeys, allChildKeys } = this.state;
              const checkedKey = JSON.parse(JSON.stringify(allChildKeys));
              const treeDatas = JSON.parse(JSON.stringify(treeDataOld));
              const checkedHaveKey = JSON.parse(JSON.stringify(allKeys)); /* 已有权限, 含父节点 */
              treeDatas.forEach((child) => {
                const index = auth.findIndex(item => item.key === child.key);
                if (index >= 0) {
                  child.disabled = false;
                  if (auth[index].flag === '0') {
                    const checkIndex = checkedKey.findIndex(item => item === auth[index].key);
                    const checkHaveIndex = checkedHaveKey.findIndex(item => item === auth[index].key);
                    checkedKey.splice(checkIndex, 1);
                    checkedHaveKey.splice(checkHaveIndex, 1);
                  }
                }
                if (child.children !== undefined && child.children.length > 0) {
                  this.handleUserAuthData(child.children, auth, checkedKey, checkedHaveKey);
                }
                this.setState({
                  checkedHaveKey,
                  checkedKeys: checkedKey,
                  treeData: treeDatas,
                  groupAuth,
                });
              });
            }
          }
        });
      }
    });
  };

  handleForm = (form) => {
    this.form = form;
  };

  handleGroupAuth = (groupAuth, authFlag) => {
    this.setState({
      groupAuth,
      authFlag,
    });
  };

  handleTreeData = (treeData, checkedKeys, allChildKeys, allChildTree) => {
    this.setState({
      treeData,
      treeDataOld: treeData,
      allKeys: checkedKeys,
      allChildKeys,
      allChildTree,
    });
    this.handleNoKey(allChildKeys, checkedKeys);
  };

  handleGroupAuthData = (data, groupAuth, checkedKey, checkedHaveKey) => {
    /* 组权限 */
    data.forEach((child) => {
      const index = groupAuth.findIndex(item => item === child.key);
      child.disabled = false;
      if (index >= 0) {
        const checkIndex = checkedKey.findIndex(item => item === groupAuth[index]);
        const checkHaveIndex = checkedHaveKey.findIndex(item => item === groupAuth[index]);
        checkedKey.splice(checkIndex, 1);
        checkedHaveKey.splice(checkHaveIndex, 1);
      }
      if (child.children !== undefined && child.children.length > 0) {
        this.handleGroupAuthData(child.children, groupAuth, checkedKey, checkedHaveKey);
      }
    });
  };

  handleNoKey = (checkedKeys, checkedHaveKey) => {
    const { allChildTree } = this.state;
    const unCheckedKey = [];
    allChildTree.forEach((child) => {
      const index = checkedKeys.findIndex(item => item === child.sKey);
      if (index === -1) {
        unCheckedKey.push(child);
      }
    });
    this.setState({ unCheckedKey, checkedHaveKey, checkedKeys });
  };

  handleUserAuthData = (data, auth, checkedKey, checkedHaveKey) => {
    data.forEach((child) => {
      const index = auth.findIndex(item => item.key === child.key);
      if (index >= 0) {
        child.disabled = false;
        if (auth[index].flag === '0') {
          const checkIndex = checkedKey.findIndex(item => item === auth[index].key);
          const checkHaveIndex = checkedHaveKey.findIndex(item => item === auth[index].key);
          checkedKey.splice(checkIndex, 1);
          checkedHaveKey.splice(checkHaveIndex, 1);
        }
      }
      if (child.children !== undefined && child.children.length > 0) {
        this.handleUserAuthData(child.children, auth, checkedKey, checkedHaveKey);
      }
    });
    return checkedKey;
  };

  handleUnAllClick = () => {
    const {
      allKeys, allChildKeys, authFlag, groupAuth,
    } = this.state;
    const checkedClickKeys = [];
    const haveCheckedClickKeys = [];
    if (authFlag === 'group') {
      this.handleNoKey([], []);
    } else if (authFlag === 'user') {
      allChildKeys.forEach((child) => {
        const index = groupAuth.findIndex(item => item === child);
        if (index === -1) {
          checkedClickKeys.push(child);
        }
      });
      allKeys.forEach((child) => {
        const index = groupAuth.findIndex(item => item === child);
        if (index === -1) {
          haveCheckedClickKeys.push(child);
        }
      });
      this.handleNoKey(checkedClickKeys, haveCheckedClickKeys);
    }
  };

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    const { loading } = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          {pageLoading ? '' :
          <div>
            <JurisdictionAllot
              {...props}
              {...state}
              handleForm={this.handleForm}
              handleSubmit={this.handleSubmit}
              handleCancel={this.handleCancel}
              onGroupsId={this.handleGroupsId}
              onUserGroupsId={this.handleUserGroupsId}
              onGroupAuth={this.handleGroupAuth}
              onTreeData={this.handleTreeData}
              onNoKey={this.handleNoKey}
              onUnAllClick={this.handleUnAllClick}
            />
          </div>}
        </Spin>
      </div>
    );
  }
}

const JurisdictionAllot = Form.create({

})((props) => {
  const {
    dispatch,
    app,
    content,
    form,
    handleForm,
    handleSubmit,
    handleCancel,
    sActiveId,
    gdsformconst,
    onGroupsId,
    onUserGroupsId,
    tabJurCon,
    tabHasJur,
    onGroupAuth,
    currentKey,
    onTreeData,
    treeData,
    checkedHaveKey,
    checkedKeys,
    onNoKey,
    onUnAllClick,
  } = props;
  const childProps = {
    dispatch, sActiveId, app, content, gdsformconst, currentKey,
  };
  const jurGroupProps = {
    componentName: 'jurGroupData',
    ...childProps,
  };
  const jurUserProps = {
    componentName: 'jurUserData',
    ...childProps,
  };
  const jurUserGroupProps = {
    componentName: 'jurUserGroup',
    ...childProps,
  };
  const jurGroupUserDataProps = {
    componentName: 'jurGroupUserData',
    ...childProps,
  };
  const tabJurConProps = {
    componentName: 'tabJurCon',
    ...childProps,
    checkedKeys,
    treeData,
  };
  const tabJurTreeConProps = {
    ...childProps,
    componentName: 'tabJurTreeCon',
    treeData,
    checkedHaveKey,
  };
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar
            {...props}
            componentName="toolJurisdictionAllot"
            onSubmit={handleSubmit}
            onBtnCancel={handleCancel}
          >
            {handleForm(form)}
          </Toolbar>
        </Header>
      </Layout>
      <Layout className={styles.clayout}>
        <Content className={styles.content}>
          <Layout className={styles.clayoutJur}>
            <Row type="flex" justify="space-between">
              <Col span={10} style={{ marginTop: 10 }}>
                <Row>
                  <Col span={12}>
                    <JurGroupData
                      {...jurGroupProps}
                      onGroupsId={onGroupsId}
                    />
                  </Col>
                  <Col span={12}>
                    <JurUserData
                      {...jurUserProps}
                      onUserGroupsId={onUserGroupsId}
                    />
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <JurGroupUserData
                      {...jurUserGroupProps}
                      onUserGroupsId={onUserGroupsId}
                    />
                  </Col>
                  <Col span={12}>
                    <JurUserGroupData
                      {...jurGroupUserDataProps}
                      onGroupsId={onGroupsId}
                    />
                  </Col>
                </Row>
              </Col>
              <Col span={14}>
                <div id="slaveTabs">
                  <Tabs size="small" className={styles.slaveTabs}>
                    <TabPane tab={tabJurCon.showName} key="1" forceRender>
                      <TabJurCon
                        {...tabJurConProps}
                        onGroupAuth={onGroupAuth}
                        onTreeData={onTreeData}
                        onNoKey={onNoKey}
                        onUnAllClick={onUnAllClick}
                      />
                    </TabPane>
                    <TabPane tab={tabHasJur.showName} key="2" forceRender>
                      <TabJurTreeCon
                        {...tabJurTreeConProps}
                      />
                    </TabPane>
                  </Tabs>
                </div>
              </Col>
            </Row>
          </Layout>
        </Content>
      </Layout>
    </Form>);
});

export default baseHigher(JurisdictionAllotComponent);
